from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .models import Comment
from notes.models import Note
from .serializers import CommentSerializer, CommentCreateSerializer

class CommentViewSet(viewsets.ModelViewSet):
    """评论视图集，处理评论的CRUD操作"""
    queryset = Comment.objects.filter(parent_comment=None).order_by('-created_at')  # 只获取顶级评论
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    
    def get_serializer_class(self):
        """根据不同的操作选择不同的序列化器"""
        if self.action == 'create':
            return CommentCreateSerializer
        return CommentSerializer
    
    @action(detail=False, methods=['get'], url_path=r'notes/(?P<note_id>[^/.]+)')
    def get_note_comments(self, request, note_id=None):
        """获取指定笔记的评论列表"""
        note = get_object_or_404(Note, pk=note_id)
        
        # 只获取顶级评论（没有父评论的评论）
        comments = Comment.objects.filter(note=note, parent_comment=None).order_by('-created_at')
        
        page = self.paginate_queryset(comments)
        if page is not None:
            serializer = self.get_serializer(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(comments, many=True, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    def perform_create(self, serializer):
        """创建评论"""
        serializer.save(user=self.request.user)
    
    def perform_destroy(self, instance):
        """删除评论前检查权限"""
        if instance.user != self.request.user:
            raise PermissionError('您没有权限删除这条评论')
        instance.delete()
    
    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def my_comments(self, request):
        """获取当前用户的所有评论"""
        comments = Comment.objects.filter(user=request.user).order_by('-created_at')
        
        page = self.paginate_queryset(comments)
        if page is not None:
            serializer = self.get_serializer(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(comments, many=True, context={'request': request})
        return Response(serializer.data)